package net.micedre.courses.service;

import net.micedre.courses.meta.CoursesUserMeta;
import net.micedre.courses.model.CoursesUser;

import org.slim3.datastore.Datastore;

import com.google.appengine.api.users.User;

public class CoursesUserService {

    /**
     * 
     * @param currentUser
     * @param create
     * @return CoursesUser : null if not exists and create==false
     *                       coursesUser if exists or newly created one if create==true
     */
    public CoursesUser getUser(User currentUser,boolean create) {
        if(currentUser == null){
            throw new NullPointerException();
        }
        CoursesUserMeta e = CoursesUserMeta.get();
        CoursesUser coursesUser;
        coursesUser = Datastore
            .query(e)
            .filter(e.email.equal(currentUser.getEmail()))
            .asSingle();
        
           
        if(coursesUser==null && create){
            coursesUser = new CoursesUser();
            coursesUser.setEmail(currentUser.getEmail());
            Datastore.put(coursesUser);
            return coursesUser;
        }
        return coursesUser;

    }
}
